var express = require('express');
var router = express.Router();
const query = require('../mysql');
const changeObjKey = require('../util/changeObjKey');
const encrypt = require('../util/encrypt.js');
/* post login listing. */
router.get('/users', async function (req, res, next) {
	let { pagenum, pagesize } = req.query.queryInfo;
	let inputQuery = req.query.queryInfo.query;
	// let searchType = req.query.queryInfo.searchType;
	let searchType = req.query.searchType;
	// 分页效果
	let result;
	// console.log('inputQuery', inputQuery);
	if (inputQuery == '') {
		let sqlStr = `select id, username, college,admin, position, 
		register_time,account from user where isLogin='1' limit ${
			(pagenum - 1) * pagesize
		},${pagesize}`;
		result = await query(sqlStr, []);
	} else {
		let sqlStr = `select id, username, college,admin, position, 
		register_time,account from user where ${searchType} like ? and isLogin='1' limit ${
			(pagenum - 1) * pagesize
		},${pagesize}`;
		result = await query(sqlStr, [`%${inputQuery}%`]);
	}

	// 查询总数量
	let sqlStr1 = `select count(*) from user`;
	let result1 = await query(sqlStr1);

	// 搜索功能
	res.send({ status: 200, data: result, total: result1[0]['count(*)'] });
});

// 业绩数量查询
router.get('/users/achievementNum', async (req, res) => {
	let { name } = req.query;
	// console.log(name, collage);
	// award 获奖
	let sqlStr0 = `select name from award where awardee like ?`,
		result0 = await query(sqlStr0, [`%${name}%`]);
	// essay 论文
	let sqlStr1 = `select name from essay where author like ?`,
		result1 = await query(sqlStr1, [`%${name}%`]);
	// patent 专利
	let sqlStr2 = `select name from patent where inventor like ?`,
		result2 = await query(sqlStr2, [`%${name}%`]);
	// project 项目
	let sqlStr3 = `select name from project where commander like ?`,
		result3 = await query(sqlStr3, [`%${name}%`]);
	// work 著作与教材
	let sqlStr4 = `select name from work where author like ?`,
		result4 = await query(sqlStr4, [`%${name}%`]);
	let resArr = [
		{ name: '获奖', length: result0.length },
		{ name: '论文', length: result1.length },
		{ name: '专利', length: result2.length },
		{ name: '项目', length: result3.length },
		{ name: '著作', length: result4.length },
	];
	res.send({ status: 200, data: resArr });
});

// 用户编辑
router.post('/users/edit', async (req, res) => {
	let userMsgEditForm = req.body.userMsgEditForm;
	console.log(req.body);
	let { username, college, position, admin, id, account, password } =
		userMsgEditForm;
	password = encrypt(password);
	let result;
	if (password === '') {
		let sqlStr = `update user set username=?,college=?,position=?,admin=?,account=? where id=?`;
		result = await query(sqlStr, [
			username,
			college,
			position,
			admin,
			account,
			id,
		]);
	} else {
		let sqlStr = `update user set username=?,college=?,position=?,admin=?,account=?,password=? where id=?`;
		result = await query(sqlStr, [
			username,
			college,
			position,
			admin,
			account,
			password,
			id,
		]);
	}

	if (result.length == 0) {
		return res.send({ status: 404, message: 'faile' });
	}
	res.send({ status: 200, message: 'success' });
});

// 人员管理
router.get('/crewManage', async function (req, res, next) {
	// console.log(req.query);
	let { pagenum, pagesize } = req.query.queryInfo;
	let inputQuery = req.query.queryInfo.query;

	// let searchType = req.query.queryInfo.searchType;
	let searchType = req.query.searchType;
	// 分页效果
	let result;
	// console.log('inputQuery', inputQuery);
	if (inputQuery == '') {
		let sqlStr = `select id, username, college,admin, position, 
		register_time,isLogin from user limit ${(pagenum - 1) * pagesize},${pagesize}`;
		result = await query(sqlStr, []);
	} else {
		let sqlStr = `select id, username, college,admin, position, 
		register_time,isLogin from user where ${searchType} like ?  limit ${
			(pagenum - 1) * pagesize
		},${pagesize}`;
		result = await query(sqlStr, [`%${inputQuery}%`]);
	}

	// 查询总数量
	let sqlStr1 = `select count(*) from user`;
	let result1 = await query(sqlStr1);

	// 搜索功能
	res.send({ status: 200, data: result, total: result1[0]['count(*)'] });
});

// 人员管理 设置
router.put('/crewManage', async function (req, res) {
	console.log(req.body);
	let { deleteUserId, isLogin } = req.body.data;
	// console.log(deleteUserId, isLogin);
	let sqlStr = `update user set isLogin =? where id = ?`;
	let result = query(sqlStr, [isLogin, deleteUserId]);
	if (!result) {
		res.send({ status: 404, message: 'delete faile' });
	}
	res.send({ status: 200, message: 'delete suceess' });
});

// 人员管理 删除
router.delete('/crewManage', async function (req, res) {
	let { deleteUserId } = req.query;
	let sqlStr = `delete from user where id = ?`;
	let result = query(sqlStr, [deleteUserId]);
	if (!result) {
		res.send({ status: 404, message: 'delete faile' });
	}
	res.send({ status: 200, message: 'delete suceess' });
});

// 业绩管理 列表
// 业绩查询
router.get('/achievementList', async (req, res) => {
	let { pagenum, pagesize } = req.query.queryInfo;
	pagenum = parseInt(pagenum);
	pagesize = parseInt(pagesize);
	let inputQuery = req.query.queryInfo.query;
	// console.log(req.query);
	// let searchType = req.query.queryInfo.searchType;
	let searchType = req.query.searchType;
	let achievementType = req.query.achievementType;
	// award 获奖
	let sqlStr0 = `select * from award`,
		result0 = await query(sqlStr0, []);
	result0.forEach((item) => {
		addAchievementType(item, '获奖');
	});
	// essay 论文
	let sqlStr1 = `select * from essay`,
		result1 = await query(sqlStr1, []);
	result1.forEach((item) => {
		addAchievementType(item, '论文');
	});
	// patent 专利
	let sqlStr2 = `select * from patent`,
		result2 = await query(sqlStr2, []);
	result2.forEach((item) => {
		addAchievementType(item, '专利');
	});
	// project 项目
	let sqlStr3 = `select * from project`,
		result3 = await query(sqlStr3, []);
	result3.forEach((item) => {
		addAchievementType(item, '项目');
	});
	// work 著作与教材
	let sqlStr4 = `select * from work`,
		result4 = await query(sqlStr4, []);
	result4.forEach((item) => {
		addAchievementType(item, '著作与教材');
	});
	let resData = [...result0, ...result1, ...result2, ...result3, ...result4];
	// console.log(resData);
	achievementType == '获奖'
		? (resData = [...result0])
		: achievementType == '论文'
		? (resData = [...result1])
		: achievementType == '专利'
		? (resData = [...result2])
		: achievementType == '项目'
		? (resData = [...result3])
		: achievementType == '著作与教材'
		? (resData = [...result4])
		: null;

	// console.log(req.query);

	// 分页效果
	let cacheData = [];
	let result = [];
	let total = 0;
	// console.log('inputQuery', inputQuery);
	if (inputQuery == '') {
		cacheData = resData.slice(
			(pagenum - 1) * pagesize,
			(pagenum - 1) * pagesize + pagesize
		);
		cacheData.forEach((item) => {
			adminChangeObjKey(item);
		});
		result = cacheData;
		total = resData.length;
	} else {
		total = 0;
		cacheData = resData;
		cacheData.forEach((item) => {
			adminChangeObjKey(item);
		});

		cacheData = cacheData.filter((item) => {
			for (const key in item) {
				if (key == searchType) {
					if (item[key].indexOf(inputQuery) !== -1) {
						return item[key] != undefined;
					}
				}
			}
		});
		console.log(cacheData);

		cacheData = cacheData.slice(
			(pagenum - 1) * pagesize,
			(pagenum - 1) * pagesize + pagesize
		);

		result = cacheData;
		total = parseInt(cacheData.length);
	}
	// console.log(result);
	console.log(total);
	res.send({ status: 200, data: result, total });
});

function adminChangeObjKey(item) {
	changeObjKey('name', 'achievementName', item);
	changeObjKey('inventor', 'author', item);
	changeObjKey('awardee', 'author', item);
	changeObjKey('commander', 'author', item);
	changeObjKey('release_unit', 'college', item);
	changeObjKey('author_unit', 'college', item);
	changeObjKey('unit', 'college', item);
	changeObjKey('affiliated_unit', 'college', item);
}

// 业绩管理 审批
router.post('/achievementStatus', async (req, res) => {
	let { status, achievementType, id } = req.body.achievementMsg;

	if (achievementType == '获奖') {
		await changeStatus('award', status, id, res);
	} else if (achievementType == '论文') {
		await changeStatus('essay', status, id, res);
	} else if (achievementType == '专利') {
		await changeStatus('patent', status, id, res);
	} else if (achievementType == '项目') {
		await changeStatus('project', status, id, res);
	} else if (achievementType == '著作与教材') {
		await changeStatus('work', status, id, res);
	}
});

// 审批状态
async function changeStatus(database, status, id, res) {
	status = status ? '1' : '0';
	let queryStr = `update ${database} set status = ? where id = ?`;
	let result = await query(queryStr, [status, id]);
	if (result.length < 1) {
		return res.send({ status: 404, message: 'faile' });
	}
	res.send({ status: 200, message: 'success' });
}

function addAchievementType(item, achievementType) {
	item['achievementType'] = achievementType;
}

module.exports = router;
